<?php

declare(strict_types=1);

namespace app\eslib;

/**
 * 数组 助手类
 * @version 1.0.0
 */
class EsArray
{
    /**
     * 一维数组转换成树形数组
     */
    public static function list2tree($list, $pid)
    {
        $tree = [];
        foreach ($list as $row) {
            if ($row['pid'] != $pid) {
                continue;
            }
            $row['children'] = [];
            // level 2
            foreach ($list as $row2) {
                if ($row2['pid'] != $row['id']) {
                    continue;
                }
                $row2['children'] = [];
                // level 3
                foreach ($list as $row3) {
                    if ($row3['pid'] != $row2['id']) {
                        continue;
                    }
                    $row3['children'] = [];
                    // level 4
                    foreach ($list as $row4) {
                        if ($row4['pid'] != $row3['id']) {
                            continue;
                        }
                        $row3['children'][] = $row4;
                    }
                    $row2['children'][] = $row3;
                }
                $row['children'][] = $row2;
            }
            $tree[] = $row;
        }
        return $tree;
    }

    /**
     * 数组转换为树形结构
     */
    public static function array2tree($source, $idField = 'id', $pidField = 'pid', $pidValue = 0)
    {
        // 将原数组转为pid为键值的一维数组
        $pidsSet = [];
        foreach ($source as $row) {
            $pidKey = 'pid_' . $row[$pidField];
            $pidsSet[$pidKey][] = $row;
        }
        function array2tree_fn($pidsSet, $idField = 'id', $pidValue = 0, $level = 0)
        {
            $pidKey = 'pid_' . $pidValue;
            $pidRows = isset($pidsSet[$pidKey]) ? $pidsSet[$pidKey] : [];
            if (!$pidRows) {
                return [];
            }
            $treeSet = [];
            foreach ($pidRows as $row) {
                $row['tree_level'] = $level;
                $row['tree_children'] = array2tree_fn($pidsSet, $idField, $row[$idField], $level + 1);
                $treeSet[] = $row;
            }
            return $treeSet;
        }
        return array2tree_fn($pidsSet, $idField, $pidValue);
    }



    /**
     * 返回数组的值
     */
    public static function getValue($data, $path, $defv = '')
    {
        if (false === strpos($path, '.')) {
            return isset($data[$path]) ? $data[$path] : $defv;
        }
        $value = $data;
        $paths = explode('.', $path);
        foreach ($paths as $name) {
            if (isset($value[$name])) {
                $value = $value[$name];
            } else {
                $value = null;
                break;
            }
        }
        return is_null($value) ? $defv : $value;
    }
}
